const { defineConfig } = require('@vue/cli-service');
const resolve = require('path').resolve;
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
const isProduction = process.env.NODE_ENV === 'production';

module.exports = defineConfig({
  publicPath: isProduction ? process.env.VUE_APP_PUBLIC_PATH : '/',
  productionSourceMap: false,
  transpileDependencies: true,
  css: {
    extract: false
  },
  devServer: {
    proxy: {
      '/api': {
        target: 'http://121.43.57.185:8089',
        pathRewrite: { '^api': '' }
      },
      '/api1': {
        target: 'http://192.168.2.91:8089',
        pathRewrite: { '^api1': '' }
      }
    }
  },
  configureWebpack: config => {
    const plugins = config.plugins;
    plugins.push(new NodePolyfillPlugin());
  },
  chainWebpack: config => {
    config.when(!isProduction, config => config.devtool('eval'));
    config.module.rule('svg').exclude.add(resolve('src/icons/svg')).end();

    config.plugin('html').tap(args => {
      args[0].title = '企业能耗管理系统';
      return args;
    });

    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons/svg'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()
      .use('svgo-loader')
      .loader('svgo-loader')
      .options({
        plugins: [
          {
            name: 'removeAttrs',
            params: {
              attrs: 'fill'
            }
          }
        ]
      })
      .end();

    // Optimization
    // https://webpack.docschina.org/plugins/split-chunks-plugin/#optimizationsplitchunks
    if (isProduction) {
      config.optimization.splitChunks({
        chunks: 'all',
        minChunks: 1,
        cacheGroups: {
          vendors: {
            name: 'chunk-vendors',
            test: /[\\/]node_modules[\\/]/,
            chunks: 'initial',
            priority: 10
          },
          element: {
            name: 'chunk-element-ui',
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/,
            priority: 20
          },
          echarts: {
            name: 'chunk-echarts',
            test: /[\\/]node_modules[\\/]_?echarts-?(.*)/,
            priority: 30
          },
          xlsx: {
            name: 'chunk-xlsx',
            test: /[\\/]node_modules[\\/]_?xlsx(.*)/,
            priority: 40
          },
          pinyin: {
            name: 'chunk-pinyin',
            test: /[\\/]node_modules[\\/]_?pinyin-?(.*)/,
            priority: 50
          }
        }
      });
    }
  }
});
